package com.dfbz.demo;

/**
 * @author lscl
 * @version 1.0
 * @intro:
 */
public class Demo01_两条线程的通信 {
    public static void main(String[] args) {


        new Thread().start();

        Shower shower = new Shower();

        new Thread() {
            @Override
            public void run() {
                try {
                    shower.show1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    shower.show2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
}

class Shower {

    int count = 1;

    public void show1() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            synchronized (Object.class) {
                while (count == 1) {
                    Thread.sleep(10);
                    System.out.print("犯");
                    System.out.print("我");
                    System.out.print("中");
                    System.out.print("华");
                    System.out.print("者");
                    System.out.println();
                    count = 2;                      // count=1
                    Object.class.notify();
                }
                Object.class.wait();

            }
        }
    }

    public void show2() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            synchronized (Object.class) {
                while (count == 2) {
                    Thread.sleep(10);
                    System.out.print("虽");
                    System.out.print("远");
                    System.out.print("必");
                    System.out.print("诛");
                    System.out.println();
                    count = 1;
                    Object.class.notify();              // 随机唤醒一条当前锁的线程
                }
                Object.class.wait();
            }
        }
    }
}